package top.csy8888.likework.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import top.csy8888.likework.common.confirm.RabbitManager;
import top.csy8888.likework.common.consts.RabbitConstants;
import top.csy8888.likework.common.consts.RedisKeyEnum;
import top.csy8888.likework.dto.LikeDTO;
import top.csy8888.likework.entity.Like;
import top.csy8888.likework.mapper.LikeMapper;
import top.csy8888.likework.service.LikeService;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author CSY
 * @date 2025 - 10 - 12
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class LikeServiceImpl implements LikeService {
    private final LikeMapper likeMapper;

    private final RedisTemplate<String, Integer> redisTemplate;

    /**
     * 注入封装的RabbitManager
     */
    private final RabbitManager<LikeDTO> rabbitManager;

    @Override
    public LikeDTO like(Integer userId,Integer postId){
        //默认没有点赞
        boolean likeStatus = false;

        if (isLike(userId,postId)){
            // 如果我已经点赞过了，那么执行该方法就应该是删除缓存中的点赞记录
            redisTemplate.opsForSet().remove(RedisKeyEnum.POST_LIKE_PREFIX.value() + postId, userId);
        }else{
            // 如果我没有点赞，那么执行该方法就是将点赞记录添加进缓存中
            likeStatus = true;
            redisTemplate.opsForSet().add(RedisKeyEnum.POST_LIKE_PREFIX.value() + postId, userId);
        }
        // 从缓存中获取到点赞该帖子的数量
        Long size = redisTemplate.opsForSet().size(RedisKeyEnum.POST_LIKE_PREFIX.value() + postId);
        LikeDTO likeDTO = new LikeDTO(userId,postId,size,likeStatus);

        rabbitManager.send(RabbitConstants.EXCHANGE_NAME,RabbitConstants.ROUTING_KEY,"likeConfirmCallback",likeDTO);

        return likeDTO;
    }

    @Override
    public Boolean isLike(Integer userId,Integer postId){
        //如果缓存中不存在
        if (Boolean.FALSE.equals(redisTemplate.hasKey(RedisKeyEnum.POST_LIKE_PREFIX.value() + postId))){
            // 查找所有的点赞记录
            List<Like> likes = likeMapper.listLikeByPostId(postId);

            // 将所有点赞该帖子的用户全部缓存到redis中
            likes.forEach(like -> {
                redisTemplate.opsForSet().add(RedisKeyEnum.POST_LIKE_PREFIX.value()+postId,like.getUserId());
                redisTemplate.expire(RedisKeyEnum.POST_LIKE_PREFIX.value() + postId, 10 , TimeUnit.MINUTES );
            });
        }
        //判断我有没有点赞该帖子
        return redisTemplate.opsForSet().isMember(RedisKeyEnum.POST_LIKE_PREFIX.value() + postId,userId);
    }

}
